<template>
	<view class="forget">

		<view class="content">
			<!-- 主体 -->
			<view class="main">
				<view class="tips">若你忘记了密码，可在此重置新密码。</view>
				<tInput v-model="username" type="text" placeholder="用户名/邮箱"></tInput>
				<tInput v-model="password" type="password" maxlength="20" placeholder="密码" isShowPass></tInput>
				<tInput v-model="code" type="number" maxlength="6" placeholder="验证码" isShowCode codeText="获取重置码"
					setTime="60" ref="runCode" @setCode="captcha()"></tInput>
			</view>

			<tButton class="wbutton" text="重置密码" :rotate="isRotate" @click.native="resetPass()"></tButton>
		</view>

	</view>
</template>

<script>
	let flag;
	let _this;
	import tInput from '@/components/tally-login/tally-input.vue' 
	import tButton from '@/components/tally-login/tally-button.vue'
	export default {
		components: {
			tInput,
			tButton
		},
		data() {
			return {
				username: "", 	 // 用户名
				password: "", 	 // 密码
				code: "", 	  	 // 验证码
				isRotate: false, // 是否加载旋转
			}
		},
		mounted() {
			flag = 1;
			_this = this;
		},
		methods: {
			// 获取验证码
			captcha() {
				if (this.username.length <= 0) {
					this.$u.toast("请输入用户名/邮箱！");
					return false;
				}
				this.$api({
					method: 'put',
					url: '/captcha/' + this.username + '/' + flag
				}).then(res => {
					if (res.code == 0) {
						// 触发倒计时
						this.$refs.runCode.$emit('runCode'); 
						// 产生60秒定时器 终止倒计时
						setTimeout(function() {
							_this.$refs.runCode.$emit('runCode',0); 
						}, 60 * 1000)
					} else {
						this.$u.toast(res.msg);
					}
				}).catch(err => {
					console.log(err)
					this.$u.toast("网络连接失败");
				});
			},
			// 重置密码
			resetPass() {
				// 判断是否加载中，避免重复点击请求
				if (this.isRotate) {
					return false;
				}
				// 加载旋转
				_this.isRotate = true
				// 封装请求信息
				let data = {
					loginName: this.username, 	
					password: this.password, 	
					code: this.code, 	
				}
				this.$api({
					method: 'post',
					url: '/system/user/forget',
					data: data
				}).then(res => {
					if (res.code == 0) {
						this.$u.toast(res.msg);
						// 终止旋转
						_this.isRotate = false
						// 进入登陆页
						uni.navigateTo({
							url: `/pages/login/login?username=${this.username}&password=${this.password}`,
							fail(err) {
								console.log(err)
							}
						});
					} else {
						// 终止旋转
						_this.isRotate = false
						this.$u.toast(res.msg);
					}
				}).catch(err => {
					// 终止旋转
					console.log(err)
					_this.isRotate = false
					this.$u.toast("网络连接失败");
				});
			}
		}
	}
</script>

<style>
	@import url("@/components/tally-login/css/icon.css");
	@import url("./css/main.css");
</style>